#coding=utf-8
import configparser
import os


class ReadIni(object):
    def __init__(self,ini_path=None):
        #判断路径是否传入路径，如果未传入，则默认conf路径下的config.ini
        if ini_path == None:
            # project_path = os.path.abspath(os.path.dirname(os.getcwd()))  # 获取上级目录
            # 获取上上级目录 os.path.abspath(os.path.join(os.getcwd(), "../.."))
            # project_path =os.path.abspath(os.path.dirname(os.getcwd()))
            # root_path = os.path.abspath(os.path.dirname(__file__)).split('shippingSchedule')[0]
            # file_name = r'E:\PythonWorkspace\ZYK_Test\LZ_Base\config.ini'
            ini_path = os.path.join(os.path.abspath(os.path.dirname(__file__)).split('Basic')[0], 'Conf', "config.ini")
            # print('配置文件路径：%s'%ini_path)
        self.ini_path = ini_path
        self.conf = self.load_ini(ini_path)

    #加载文件
    def load_ini(self,file_name):
        conf = configparser.ConfigParser()
        conf.read(file_name,encoding='utf-8')
        return conf

    #获取属性值
    def get_value(self,section,key):
        data = self.conf.get(section,key)
        return data

    # 修改属性值，属性不存在则添加属性
    def set_value(self,section,key,value):
        self.conf.set(section,key,value)
        with open(self.ini_path, "w",encoding='utf-8') as f:
            self.conf.write(f)

    #删除属性
    def del_value(self,section,key):
        self.conf.remove_option(section,key)
        with open(self.ini_path, "w",encoding='utf-8') as f:
            self.conf.write(f)

    # 获取属性值
    def getint_value(self, section, key):
        data = self.conf.getint(section, key)
        return data

    #添加section
    def add_section(self,section,dict=None):
        if not self.conf.has_section(section):
            if dict:
                self.conf[section] = dict
            else:
                """
                config["DEFAULT"] = {'ServerAliveInterval': '45',
                                 'Compression': 'yes',
                                 'CompressionLevel': '9'}
                """
                self.conf.add_section(section)
            with open(self.ini_path, 'w',encoding='utf-8') as f:
                self.conf.write(f)


if __name__ == '__main__':
   read_init = ReadIni()
   print('读取 %s'%read_init.get_value('excel','filename'))
   list = [123,233,222]
   read_init.set_value('casemoudel','dddddd',str(list))
   print('读取 %s' % read_init.get_value('casemoudel', 'dddddd'))

